package com.nba.common.framework;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nba.common.exception.CustomException;
import com.nba.common.web.httpobjects.BusinessMsg;
import com.nba.common.web.httpobjects.MsgResult;
import com.nba.common.exception.BaseServiceException;

@ControllerAdvice
public class GlobalExceptionHandler {
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public MsgResult handleException(Exception ex, HttpServletRequest request) {
		return new MsgResult(Status.ServerException.toString(), new BusinessMsg(0, ex.getMessage()));
	}

	@ExceptionHandler(BaseServiceException.class)
	@ResponseBody
	public MsgResult handleBusinessException(BaseServiceException ex, HttpServletRequest request) {
	    if(ex.getMessage() != null){
	        return new MsgResult(Status.BusinessException.toString(), new BusinessMsg(ex.getCode(), ex.getMessage().replaceFirst(ex.getCode()+":", "")));
	    }else{
	        return new MsgResult(Status.BusinessException.toString(), new BusinessMsg(ex.getCode(), ex.getMessage()));
	    }
	}
	
	@ExceptionHandler(CustomException.class)
	@ResponseBody
	public MsgResult handleBusinessException(CustomException ex, HttpServletRequest request) {
	    if(ex.getMessage() != null){
	        return new MsgResult(Status.NoLoginException.toString(), new BusinessMsg(ex.getCode(), ex.getMessage().replaceFirst(ex.getCode()+":", "")));
	    }else{
	        return new MsgResult(Status.NoLoginException.toString(), new BusinessMsg(ex.getCode(), ex.getMessage()));
	    }
	}

	private void clearCientInfo(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
			for (Cookie cookie : cookies) {
				cookie.setMaxAge(0);
				cookie.setValue("");
				cookie.setDomain(".jsk.com");
				cookie.setPath("/");
				response.addCookie(cookie);
			}
		}
	}

}